하는 방법 필터 타이프 라이터 배열에 따라 아마 정의되지 않은 날짜로 문자열 품목 개체설턴트를 제공합니다.

0

질문

API 으로 결과를 반환하는 개체 이상의 천한 값은 다음과 같은 형식은:

result = {
  "items": [
            {
              "Name": "abc",
              "CreatedOn": "2017-08-29T15:21:20.000Z",
              "Description": "xyz"
            },
            {
              "Name": "def",
              "CreatedOn": "2021-05-21T15:20:20.000Z",
              "Description": "cvb"
            }
          ]
}

내가 좋아하는 필터는 항목에서는 개체는 후 90 일 이상 하지 않고 반복하여 사용하는 모든 항목에 대한 반복입니다. 다시 말해서 내가 좋아하는 다음과 같은 것이 아래 그러나 이것은 작동하지 않는다.

var currentDate = new Date();
var newResult = result.items?.filter(function(i) {
    return ((currentDate - Date.parse(i.CreatedOn)) > 90);
}

에 따라 IDE 시설 CreatedOn 의 형식 string | undefined 그래서 그것을 발생한 오류:형식의 인수를 'string | undefined' 해당 옵션을 선택하려의 매개변수 유형 'string'. 유형 'undefined' 에 할당할 수 없 유형 'string'.

javascript typescript
2021-11-24 03:43:04
3

최고의 응답

2

의 프로젝트에 어딘가에 당신이 무언가가 다음과 같 다:

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;
}

typeinterface (단지 확인하십시오 사용 class 을 설명하 JSON data,JSON 으로 object 데이 될 수 없습니다 class 인스턴스 때문에 생성자를 실행되지 않).

또한,당신이 사용해야 camelCasePascalCase을 위해,회원 속성입니다. 그래서 같은 이름을 사용 createdOnCreatedOn 에서 생성되는 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;
} );

하지만 개인적으로 나는 그것을 할 거라고는 초기 filtermap 단계:

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 );

더 나은 솔루션:

  • 당신의 제어에 내용을 생성할 수 있습니다 다음을 보장하는 일정(또는 모두)항목 속성이 항상 설정됩니다(그리고 결코 undefinednull),도록 보장할 수 있는 경우에는 모든 3 개은 항상 설정(적 nullundefined다)다음 업데이트 유형/인터페이스다.

    interface ResultItem {
        readonly name       : string;
        readonly createdOn  : string;
        readonly description: string;
    }
    
    • 참고 camelCase 속성입니다.
    • 불변성 데이터의 큰 혜택입니다,그래서인지 확인 인터페이스 속성은 모든 readonly모든 배열 readonly T[]며,그 특성은 주석으로 ? | null| undefined 으로 적절한 대신의 단순히 가는 방법 중 하나 또는 다른입니다.
  • 그래서 사용할 수 있는지 확인 strictNullCheckstsconfig.jsontsc 옵션! -실제로,단지 사용 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 );
2021-11-24 04:21:52
1

고 가정하고 당신은 인터페이스는 다음과 같이 정의한다...

interface Item {
  Name: string,
  Description: string,
  CreatedOn?: string // note the optional "?"
}

interface Result {
  items?: Item[] // also optional according to your code
}

려면 필터는 항목에 대한은 90 일 이상(제외 없는 사람들 CreatedOn음)도

interface ItemWithDate extends Omit<Item, "CreatedOn"> {
  CreatedOn?: Date // real dates, so much better than strings
}

const result: Result = { /* whatever */ }

const items: ItemWithDate[] = result.items?.map(({ CreatedOn, ...item }) => ({
  ...item,
  CreatedOn: CreatedOn ? new Date(CreatedOn) : undefined
})) ?? []

const dateThreshold = new Date()
dateThreshold.setDate(dateThreshold.getDate() - 90)

const newItems = items.filter(({ CreatedOn }) =>
  CreatedOn && CreatedOn < dateThreshold)

호환되지 않습니터 Demo

2021-11-24 04:01:43

내 무례를 용서(그리고 그것은 꽤 큰 구멍이 나의 것),무엇 ({ CreatedOn, ...item }) => ({ 을 정확하게 수행? 나는 본 적이 확산 연산자 ... 함수에서 사용되는 매개 변수 목록은 동일한 시간에 객체로-다.
Dai

@다이 추출물이 어떤 이라는 속성(CreatedOn다)및 유지 나머지 부분에서 item. 기본적으로 바로가기 (obj) => { const { a, b, ...rest } = obj; ...
Phil
-1

코드가 없 ) 의 필터링 기능

var currentDate = new Date();
var newResult = result.items?.filter(function(i) {
    return ((currentDate - Date.parse(i.CreatedOn)) > 90);
}  ) //<= misss


2021-11-24 04:23:03

귀하의에 응답하지 않 주소 tsc아 입력 오류가 있습니다.
Dai

으로의 현재 기록,당신의 대답은 불분명합니다. 십시오 편집 을 추가 정보는 다른 사람들이 이해하도록 돕기 위해 어떻게 이 문제를 해결이 물었다. 을 찾을 수 있습하는 방법에 대한 자세한 정보를 쓰기 좋은 도움말 센터에서.
Community

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................