의 프로젝트에 어딘가에 당신이 무언가가 다음과 같 다:
interface Result {
readonly items: readonly ResultItem[] | null;
}
interface ResultItem {
readonly Name : string;
readonly CreatedOn : string | undefined;
readonly Description: string;
}
또는 이(또는 그와 유사한):
type Result = {
items?: ResultItem[];
}
interface ResultItem {
Name : string;
CreatedOn? : string;
Description: string;
}
거 type
대 interface
(단지 확인하십시오 사용 class
을 설명하 JSON data,JSON 으로 object
데이 될 수 없습니다 class
인스턴스 때문에 생성자를 실행되지 않).
또한,당신이 사용해야 camelCase
지 PascalCase
을 위해,회원 속성입니다. 그래서 같은 이름을 사용 createdOn
대 CreatedOn
에서 생성되는 JSON.
다행히 당신을 변경할 필요가 없 유형/인터페이스,다만 변화하는 타이프 라이터를 안전하게 확인 .CreatedOn
과 하는 Date.parse
반환하지 않았 NaN
. 그래서 다음과 같:
- 이
result.items ?? []
부분이기 때문에 당신의 게시물을 의미한 result.items
이 null 을 허용하거나 어쩌면-undefined
.
- 참고 사용하는 경우
map
로 =>
스타일의 기능이 필요할 수 있는 랩 개체-리터럴 ()
그래서 JS 엔진 해석하지 않 {
고 }
블록으로 구분 기호.
const result: Result = ...
const currentDate = new Date();
const newResult = (result.items ?? []).filter( e => {
if( typeof e.CreatedOn === 'string' ) {
const parsed = Date.parse( e.CreatedOn );
if( !isNaN( parsed ) ) {
return ( currentDate - parsed ) > 90;
}
}
return false;
} );
하지만 개인적으로 나는 그것을 할 거라고는 초기 filter
고 map
단계:
const items = result.items ?? [];
const currentDate = new Date();
const newResult = items
.filter( e => typeof e.CreatedOn === 'string' )
.map( e => ( { ...e, CreatedOn2: Date.parse( e.CreatedOn ) } ) )
.filter( e => !isNaN( e.CreatedOn2 ) )
.filter( e => ( currentDate - e.CreatedOn2 ) > 90 ) );
또는 단순 더:
const items = result.items ?? [];
const currentDate = new Date();
const newResult = items
.filter( e => typeof e.CreatedOn === 'string' )
.map( e => Object.assign( e, { createdOn2: Date.parse( e.CreatedOn ) )
.filter( e => !isNaN( e.CreatedOn2 ) && ( currentDate - e.CreatedOn2 ) > 90 );
더 나은 솔루션:
당신의 제어에 내용을 생성할 수 있습니다 다음을 보장하는 일정(또는 모두)항목 속성이 항상 설정됩니다(그리고 결코 undefined
나 null
),도록 보장할 수 있는 경우에는 모든 3 개은 항상 설정(적 null
나 undefined
다)다음 업데이트 유형/인터페이스다.
interface ResultItem {
readonly name : string;
readonly createdOn : string;
readonly description: string;
}
- 참고
camelCase
속성입니다.
- 불변성 데이터의 큰 혜택입니다,그래서인지 확인 인터페이스 속성은 모든
readonly
모든 배열 readonly T[]
며,그 특성은 주석으로 ?
나 | null
나 | undefined
으로 적절한 대신의 단순히 가는 방법 중 하나 또는 다른입니다.
그래서 사용할 수 있는지 확인 strictNullChecks
에 tsconfig.json
나 tsc
옵션! -실제로,단지 사용 strict
항상!
도 변경하십시오 JSON DTO 서 사용 string
표현의 날짜(이 있습 gurantees 에 대한 timezone?) 하는 기본적으로 읽을 수 있는 Unix timestamp(밀리초 단위),할 수있는 방법에 문제가 발생하지 않도록 Date.parse
전체:
예를 들어:
결과입니다.cs:
public class ResultItem
{
[JsonProperty( "createdOn" )]
public DateTimeOffset CreatedOn { get; }
[JsonProperty( "createdOnUnix" )]
public Int64 CreatedOnUnix => this.CreatedOn.ToUnixTimeMilliseconds();
}
결과입니다.ts:
interface ResultItem {
readonly createdOn : string;
readonly createdOnUnix: number;
}
const ninetyDaysAgo = new Date();
ninetyDaysAgo.setDate( ninetyDaysAgo.getDate() - 90 );
const newResult = items.filter( e => new Date( e.createdOnUnix ) < ninetyDaysAgo );
...는 단일 온라인 작업입니다.
위 만들 수 있습니다 더 간단으로 유닉스의 타임 스탬프는 정수를 직접 비교,도 new Date()
할 수 있는 피부 filter
다음과 같이:
const ninetyDaysAgo = new Date();
ninetyDaysAgo.setDate( ninetyDaysAgo.getDate() - 90 );
const ninetyDaysAgoUnix = ninetyDaysAgo.getTime();
const newResult = items.filter( e => e.createdOnUnix < ninetyDaysAgoUnix );
({ CreatedOn, ...item }) => ({
을 정확하게 수행? 나는 본 적이 확산 연산자...
함수에서 사용되는 매개 변수 목록은 동일한 시간에 객체로-다.